﻿using System;
using System.Web.UI;

namespace SPCountdown.SPCountdownWebPart
{
	public partial class SPCountdownWebPartUserControl : UserControl
	{
		public SPCountdownWebPart WebPart { get; set; }

		public SPCountdownWebPartUserControl()
		{
			PreRender += SPCountdownWebPartUserControl_PreRender;
		}

		void SPCountdownWebPartUserControl_PreRender(object sender, EventArgs e)
		{
			// parse date from properties
			var targetDateString = string.Format("{0},{1},{2},{3},{4},{5}",
												 WebPart.TargetDate.Year,
												 WebPart.TargetDate.Month - 1, //uses 0-based index
												 WebPart.TargetDate.Day,
												 WebPart.TargetDate.Hour,
												 WebPart.TargetDate.Minute,
												 WebPart.TargetDate.Second);

			// js sources
			const string jqueryScript = "<script type='text/javascript' src='/_layouts/SPCountdown/js/jquery-1.10.2.min.js'></script>";
			const string countdownScript = "<script type='text/javascript' src='/_layouts/SPCountdown/js/jquery.countdown.min.js'></script>";

			// create javascript implementing countdown
			const string jsCountdownFormat = "<script type='text/javascript'>$(function () {{var targetDate = new Date({0});$('#defaultCountdown').countdown({{until: targetDate}});}});</script>";
			var jsCountdown = string.Format(jsCountdownFormat, targetDateString);

			// register client scripts
			var cs = Page.ClientScript;

			if (!cs.IsClientScriptBlockRegistered("jQuery"))
				cs.RegisterClientScriptBlock(
					GetType(),
					"jQuery",
					jqueryScript);

			if (!cs.IsClientScriptBlockRegistered("jsCountdownScript"))
				cs.RegisterClientScriptBlock(
					GetType(),
					"jsCountdownScript",
					countdownScript);

			if (!cs.IsClientScriptBlockRegistered("jsCountdown"))
				cs.RegisterClientScriptBlock(
					GetType(),
					"jsCountdown",
					jsCountdown);
		}

		protected void Page_Load(object sender, EventArgs e)
		{

		}

	}
}
